<?php
//商家列表
namespace app\ausadmin\controller;
use app\ausadmin\controller\Common;
use app\common\logic\Upload;
use think\Request;
use think\Db;
use think\File;
use think\Config;
use think\Session;
use think\Cookie;
use Godok\Org\FileManager;
use Qcloud\cos\Api;
use app\common\logic\Seller as Lseller;

class Seller extends Common
{
    private $sellerObj;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->sellerObj = new Lseller();
    }

    //商户列表
	public function sellerlist(){
		//定义每页显示记录数
		$pages = 20;
		//定义where条件
        $where = [];
		$pageParam    = ['query' =>[]];
		//判断是否有按商户名称查询
		if(!empty(input('name'))){
			$where .= ' AND a.name LIKE '."'%".input('name')."%' ";
			$pageParam['query']['name'] = input('name');
			$this->assign('name',input('name'));
		}
		
		//判断是否按所在区域查询
		if(!empty(input('area'))){
			$where .= ' AND a.area LIKE '."'%".input('area')."%'";
			$pageParam['query']['area'] = input('area');
			$this->assign('area',input('area'));
		}
		/*$u = Config::get('auth.table_user');//定义用户表
		$list= Db::name( 'seller')
				->alias('a')
				->join("$u b",'a.oid = b.oid and a.salesman = b.id')
				->field('a.id,a.salesman,a.phone,a.area,a.addr,a.longitude,a.latitude,a.picture,a.shopstart,a.shopend,a.averageprice,a.brokerage,a.name,b.nickname')
                ->where($where)
                ->order('a.create_time DESC')
				->paginate($pages, false, $pageParam);*/
		//$u = Config::get('operator_users');//定义用户表
		$list = Db::name('seller')
				->where($where)
				->order('id desc')
				->paginate($pages, false, $pageParam);
        $this->assign('status', $this->sellerObj->getStatus());
        $agent = $this->sellerObj->getAgent();
        $this->assign('agent', $agent['agent']);
        $this->assign('sale', $agent['sales']);
		$this->assign('list',$list);
		return $this->fetch();
	}


	public function add(){
        $id = Request::instance()->param('id');
        $id = intval($id);
        if ($id) {
            $sellerInfo = Db::name('seller')->where(['id' => $id])->find();
        } else {
            $sellerInfo = [];
        }
		if ( Request::instance()->isPost()) {
            $data = input();//获取所有数据
            if ($id) {
                $result = $this->sellerObj->editSeller($data);
            } else {
                $result = $this->sellerObj->addSeller($data);
            }
            return $result;
		}
        // 获取所有代理商和地推
        $agentInfo = $this->sellerObj->getAgent();
        $this->assign('agent',$agentInfo['agent']);
        $this->assign('status', $this->sellerObj->getStatus());
        $this->assign('sales',$agentInfo['sales']);

        //如果是编辑
        if ($sellerInfo) {
            $image_list = explode(',', trim($sellerInfo['picture'], ','));
            $allImage = [];

            $url = config('txyunview');
            $picture = '';
            foreach ($image_list as $image) {
                $name = explode('/', $image);
                $name = array_pop($name);
                $allImage[] = ['name' => $name, 'url' => $url.$image];
                $picture .= $url.$image.',';
            }
            $picture = trim($picture, ',');
            $sellerInfo['shopstart'] = $this->sellerObj->parseTime($sellerInfo['shopstart']);
            $sellerInfo['shopend'] = $this->sellerObj->parseTime($sellerInfo['shopend']);
            $this->assign('picture', $picture);
        } else {
            $allImage = [];
        }
        $this->assign('all_img', json_encode($allImage));
        // 省份
        $provinceTmp = Db::name('address')->where("addr_pid=0")->field('addr_id,addr_name')->select();
        $province = [];
        foreach($provinceTmp as $val){
            $province[$val['addr_id']] = $val;
            $pids[] = $val['addr_id'];
        }
        $this->assign('province',$province);
        // 城市
        $cityTmp = Db::name('address')->where("addr_pid in (".implode(",",$pids).")")->field('addr_id,addr_name,addr_pid')->select();
        $city = [];
        foreach($cityTmp as $val){
            $city[$val['addr_pid']][] = $val;
        }
        $this->assign('city',$city);
        $this->assign('info', $sellerInfo);
		return $this->fetch();
	}

	/**
	 *文件上传
	 *
	 */
	public function file_upload()
    {
        $fileObj = new Upload();
        $dstPath = 'operator/Seller/';
        $res = $fileObj->upload('img_file', $dstPath, 1024*1024*10);
        if ($res['code'] == 0) {
            return json($res['msg']);
        } else {
            return json($res['msg']);
        }
    }

	public function edit($id='',$data= ''){
		
		if ( Request::instance()->isPost()) {
			$data['id']= input('id');
			$data['name']= input('name');
			$data['phone']= input('phone');
			$data['contacts']= input('contacts');
			$data['mobile']= input('mobile');
			$data['brokerage'] = input('brokerage');
			$data['picture'] = trim(input('picture'),"\n");
			$data['province']= input('province');
			$data['addr']= input('addr');
			$data['city']= input('city');
			$data['longitude']= input('longitude');
			$data['latitude']= input('latitude');
			$data['agency'] = input('agency');
			$data['salesman'] = input('salesman');
			$data['create_user'] = session('adminid');
			$name = input('name');
            $sid = input('id');
			$check = Db::name('seller')->where('id','<>',$sid)->where('name',$name)->find();
			if($check){
				return ['code'=>-1050, 'msg'=>'商户名称已存在!'];
			}
			if(Db::name( 'seller')->update($data)){
		    	//$this->redirect('sellerlist');
		    	$oid = session('oid');$m = 'ausadmin'; $c = 'Seller'; $action="edit"; $uid=session('adminid'); $querystring = '编辑商户信息';$ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
		    	return ['code'=>0, 'msg'=>'修改成功！'];
    		}else{
    			//$this->error('添加失败！');
    			return ['code'=>-1050, 'msg'=>'修改失败！'];
    		}

		}else{
			$id =  Request::instance()->get('id','','number_int');
			if(!empty($id)){
				$where = 'id = '.$id;
				$jquery = Db::name('seller')->where($where)->find();

                $init_image = [];
                $con = [];
                if(!empty($jquery['picture'])){
                    $init_image = trim($jquery['picture']);
                    $init_image = explode("\n",$init_image);
                    $init_image = array_map(function($img){
                        return Config::get('resourceurl').$img;
                    },$init_image);
                    foreach($init_image as $key=>$val){
                        $con[] = ["caption"=> "","size"=>329892,"width"=>"120px","url"=>"{$val}","key"=>$key+1];
                    }
                }

				$this->assign('init_image',json_encode($init_image));
				$this->assign('con',json_encode($con));
				$this->assign('v',$jquery);
                // 获取所有代理商
                $agentTmp = Db::name('agent')->where("is_use=1 and type=1")->field('id,agent_name')->select();
                $agent = [];
                foreach($agentTmp as $val){
                    $agent[$val['id']] = $val;
                }
                $this->assign('agent',$agent);
         
                // 获取所有地推
                $agentTmp = Db::name('agent')->where("is_use=1 and type=2")->field('id,agent_name,belong_agent')->select();
                $sales = [];
                foreach($agentTmp as $val){
                    $sales[$val['belong_agent']][] = $val;
                }
                $this->assign('sales',$sales);
          
                // 省份
                $provinceTmp = Db::name('address')->where("addr_pid=0")->field('addr_id,addr_name')->select();
                $province = [];
                foreach($provinceTmp as $val){
                    $province[$val['addr_id']] = $val;
                    $pids[] = $val['addr_id'];
                }
                $this->assign('province',$province);
          
                // 城市
                $cityTmp = Db::name('address')->where("addr_pid in (".implode(",",$pids).")")->field('addr_id,addr_name,addr_pid')->select();
                $city = [];
                foreach($cityTmp as $val){
                    $city[$val['addr_pid']][] = $val;
                }
                $this->assign('city',$city);
				return $this->fetch();
			}else{
				die('非法访问!');
			}
			
		}
		
	}

	public function delete($id=''){
		$id =  Request::instance()->get('id','','number_int');
		$data['id'] = $id;
		$data['is_delete'] = 0; 
		if(Db::name( 'seller')->update($data)){
    			//$this->redirect('index');
    		$ret = Db::name('charecabinet')->where('sid',$id)->find();
    		Db::name('charecabinet')->where('id',$ret['id'])->setField('sid', 0);
    		$oid = session('oid');$m = 'ausadmin'; $c = 'Seller'; $action="delete"; $uid=session('adminid'); $querystring = '删除商户 '.$id.' 信息';$ip = get_ip();$os = get_os();
                    set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
    		return ['code'=>0, 'msg'=>'删除成功！'];
		}else{
			return ['code'=>-1050, 'msg'=>'删除失败！'];
		}

	}

    /**
     *更改状态
     * @param string $id
     * @return
     */
    public function change_status($id = '')
    {
        return $this->sellerObj->changeStatus($id);
    }


}